package com.shu.shiro.shiro;

import com.alibaba.druid.util.StringUtils;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

public class ShiroSessionManager extends DefaultWebSessionManager {

    private static final String AUTHORIZATION="authToken";
    private static final String REFERENCED_SESSION_ID_SOURCE="Stateless request";
    public ShiroSessionManager(){
        super();
    }

    @Override
    public Serializable getSessionId(ServletRequest request, ServletResponse respone) {
        //如果没有携带id参数则按照父类的方式在cookie中获取
        String id=WebUtils.toHttp(request).getHeader(AUTHORIZATION);
        if (StringUtils.isEmpty(id)){
            return super.getSessionId(request,respone);
        }
        else {
            //如果请求头有authToken则其值为sessionid
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE,REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID,id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID,Boolean.TRUE);

            return id;
        }
    }
}
